<template>
    <div class="scheduling">
        <a-modal width="90%" :visible="visible" title="预警生产计划" @cancel="modalCancel" class="yuan-modal scheduling-modal"
            :dialog-style="{ top: '20px' }" :confirm-loading="saveLoading">
            <a-spin tip="Loading..." :spinning="formLoading">
                <div class="yuan-container">

                    <div class="page-top" v-if="parentInfo&&parentInfo.id">
                        <span class="page-title">{{parentInfo.name}}</span>
                        <span style="margin-left:20px">计划日期：{{formData.nowDate}}</span>
                        <span style="margin-left:20px">标准：{{parentInfo.standard}}</span>
                        <a-button type="primary" class="filter-list" style="float:right"
                            @click="showSimulatedPlan">模拟计算</a-button>
                    </div>

                    <a-form-model layout="inline" class="yuan-form" ref="form" :model="formData"
                        :label-col="{ style: { width: '150px' } }" :wrapper-col="{ style: { width: 'calc(100% - 160px)' } }">
                        <div class="form-panel">
                            <div class="form-panel-box">
                                <a-form-model-item class="yuan-form-item yuan-form-col5" label="生产计划编号">
                                    <span class="mast-ico"></span>
                                    <a-input class="yuan-form-input" v-model="formData.planSerial"
                                        placeholder="请输入生产计划编号"></a-input>

                                </a-form-model-item>
                                <a-form-model-item class="yuan-form-item yuan-form-col5" label="负责人" prop="personId">
                                    <span class="mast-ico"></span>
                                    <a-select class="yuan-form-input" v-model="formData.personId" placeholder="请选择"
                                        :filter-option="$filterOption" show-search>
                                        <a-select-option :value="item.userId" v-for="item in accountList"
                                            :key="item.userId">{{item.name}}</a-select-option>
                                    </a-select>
                                </a-form-model-item>

                                <div class="clear-both"></div>
                                <div style="display:flex;width:100%;margin-top:20px" v-for="item in alarmData">
                                    <div style="margin-right:20px;font-size:16px">
                                        产品大类：{{item.inventoryType}}
                                    </div>
                                    <div style="flex-grow:1;background-color: #f8f8f8;padding:10px 0">
                                        <div style="margin-bottom:10px">
                                            <span style="margin-left:20px">可供销售天数：{{item.availableSellDay}}天</span>
                                            <span style="margin-left:20px">
                                                差量：
                                                <span class="c-danger font-bignum">{{item.differenceNum | toDecimalNoZero(0)}}</span>
                                                袋
                                            </span>
                                            <span style="margin-left:20px">
                                                需求量：
                                                <span class="c-warning font-bignum"> {{item.dayRequirement}}</span>
                                                袋</span>
                                            <span style="margin-left:20px">成品库存量：
                                                <span class="c-success font-bignum"> {{item.stockNum}}</span>
                                                袋</span>
                                        </div>
                                        <a-form-model-item class="yuan-form-item yuan-form-col5" label="计划包装量">
                                            <a-input suffix="袋" class="yuan-form-input" v-model="item.formDifferenceNum"
                                                placeholder="请输入计划包装量" @input="proNumChange"></a-input>
                                            <span style="margin-left:10px">{{item.loadingQuantity}} g/袋</span>
                                        </a-form-model-item>
                                        <a-form-model-item class="yuan-form-item yuan-form-col5" label="配方颗粒(颗粒)投入量">
                                            <a-input suffix="kg" class="yuan-form-input" v-model="item.formInputNum"
                                                placeholder="请输入" @input="inNumChange"></a-input>
                                        </a-form-model-item>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </a-form-model>
                    <PlanListVue ref="planListVue" v-if="planSimulation&&planSimulation.length>0 && visible"
                        :planSimulation="planSimulation" :alarmData="alarmData" :parentInfo="parentInfo" />
                </div>
            </a-spin>
            <template slot="footer">
                <template>
                    <a-button type="primary" @click="clickSave">
                        确认排产
                    </a-button>
                    <a-button type="primary" @click="savePlan('2')">
                        关闭计划
                    </a-button>
                </template>

                <a-button @click="modalCancel">
                    取消
                </a-button>
            </template>
        </a-modal>

        <SimulatedPlanVue :visible="simulatedPlanVisible" @closeModal="() => simulatedPlanVisible = false" :bigProNum="0"
            :smallProNum="0" :parentInfo="parentInfo" />
        <SureModel :visible="sureVisible" @closeModal="() => sureVisible = false" :sureInfo="sureInfo" @sureClose="sureClose" />
    </div>
</template>

<script lang="ts">
import warningApi from "@/api/warningApi";
import { format, toDecimalNoZero } from "@/utils";
import { Vue, Component, Prop, Watch } from "vue-property-decorator";
import SimulatedPlanVue from "./simulatedPlan.vue";
import PlanListVue from "./planListV2.vue";
import SureModel from "./sureModel.vue";

@Component({ name: "TPL", components: { SimulatedPlanVue, PlanListVue,SureModel } })
export default class index extends Vue {
    @Prop({ default: "" }) visible!: boolean;
    @Prop({ default: {} }) parentInfo!: any; // 父级传入品类信息
    @Watch("visible")
    visibleChange() {
        if (this.visible) {
            this.pageInit();
            this.formData.nowDate = format(new Date(), "yyyy年MM月dd号");
        }
    }
    formLoading = false;
    saveLoading = false;
    formData: any = {
        nowDate: "",
        personId: undefined,
    };
    closeModal() {
        this.formData = { nowDate: "", personId: undefined };
        setTimeout(() => {
            (this.$refs.form as any).resetFields();
        }, 200);
        this.$emit("closeModal");
    }
    modalCancel() {
        this.closeModal();
    }
    alarmData: any[] = [];
    async pageInit() {
        this.formData.planSerial = this.getStorageBatch();
        // 获取负责人列表
        await this.getUserList();
        // 获取成品差量，需求量等基础数据
        await this.getAlarmGetData();
        await this.getKeLiNum();
    }
    simulatedPlanVisible = false;
    showSimulatedPlan() {
        this.simulatedPlanVisible = true;
    }
    /**
     * 获取颗粒数量
     */
    async getKeLiNum() {
        try {
            this.formLoading = true;
            const alarmData = this.alarmData;
            let count = 0;
            let len = alarmData.length;

            alarmData.forEach(async (item, idx) => {
                const keliRes = await warningApi.getKeLiNum({
                    id: this.parentInfo.id,
                    num: item.formDifferenceNum || 0,
                    inventoryType: item.inventoryType,
                });
                alarmData[idx].formInputNum = keliRes.data.num;
                alarmData[idx].sellDay = keliRes.data.sellDay;
                count++;
                if (count >= len) {
                    this.formLoading = false;
                    this.alarmData = alarmData;
                    this.reviewPlan();
                }
            });
        } finally {
            //
        }
    }
    simulationTimer: number | null = null;
    proNumChange() {
        // 加个防抖
        if (this.simulationTimer) {
            clearTimeout(this.simulationTimer);
        }
        this.simulationTimer = setTimeout(async () => {
            await this.getKeLiNum();
        }, 500);
    }
    inNumChange() {
        // 加个防抖
        if (this.simulationTimer) {
            clearTimeout(this.simulationTimer);
        }
        this.simulationTimer = setTimeout(async () => {
            this.reviewPlan();
        }, 500);
    }
    /**
     * 根据颗粒数量获取计划列表
     */
    planSimulation = [];
    async reviewPlan() {
        try {
            this.formLoading = true;
            let total = 0;
            this.alarmData.forEach((item) => {
                total += Number(item.formInputNum);
            });
            const res = await warningApi.getKeLiFeeding({
                id: this.parentInfo.materialId,
                num: total,
            });
            this.planSimulation = res.data.map((item) => {
                const surplus = Number(item.surplus);
                return {
                    ...item,
                    surplus: toDecimalNoZero(surplus),
                };
            });
        } finally {
            this.formLoading = false;
        }
    }

    accountList: any[] = [];
    async getUserList() {
        if (this.accountList && this.accountList.length > 0) return;
        try {
            this.formLoading = true;
            const res = await warningApi.getAccountList({});
            this.accountList = res.data?.rows || [];
        } finally {
            this.formLoading = false;
        }
    }
    async getAlarmGetData() {
        try {
            this.formLoading = true;
            const res = await warningApi.alarmGetData({ id: this.parentInfo.id });

            const arr = res.data || [];
            const alarmData = arr.map((item) => {
                return {
                    ...item,
                    formDifferenceNum: toDecimalNoZero(item.differenceNum,0),
                    formInputNum:  toDecimalNoZero(item.inputNum,0),
                };
            });
            this.alarmData = alarmData;
        } finally {
            this.formLoading = false;
        }
    }
    async clickSave() {
        if(!this.formData.personId){
            this.$message.error('请选择负责人')
            return
        }
        let inputNum = 0;
        const planList: any[] = [];
        this.alarmData.forEach((item) => {
            inputNum += item.formInputNum;
            planList.push({
                inventoryType: item.inventoryType,
                availableSellDay: item.availableSellDay,
                differenceNum: item.differenceNum,
                surplus: item.stockNum,
                packNum: item.formDifferenceNum,
                loadingQuantity: item.loadingQuantity,
                inputNum: item.formInputNum,
                dayRequirement: item.dayRequirement,
                stockNum: item.stockNum
            });
        });

        const findUser = this.accountList.find((item: any) => item.userId === this.formData.personId) || { name: "", userId: "" };

        // 获取计划详情
        const processPlanDetailList = (this.$refs["planListVue"] as any).getPageInfo();
        if(processPlanDetailList===false){
            return
        }
        const data = {
            inputNum,
            materialId: this.parentInfo.id,
            materialName: this.parentInfo.name,
            materialType: this.parentInfo.materialType,
            person: findUser.name,
            personId: findUser.userId,
            planSerial: this.formData.planSerial,
            planList:JSON.stringify(planList),
            standard: this.parentInfo.standard,
            type: "成品",
            processPlanDetailList
        };

        this.sureVisible = true;
        this.sureInfo = data;
    }
    sureInfo={}
    sureVisible = false;

    getStorageBatch() {
        const time = new Date().getTime();
        let randomNumber: number | string = Math.floor(Math.random() * 100);
        // 如果随机数小于10，则在前面添加一个0
        if (randomNumber < 10) {
            randomNumber = "0" + randomNumber;
        }
        return format(time, "MMddhhmm" + randomNumber);
    }
    sureClose(){
        this.closeModal()
        this.$emit("resetList");
    }
}
</script>

<style lang="scss">
.scheduling-modal {
    .page-top {
        padding-bottom: 20px;
        border-bottom: solid 1px #eee;
    }
    .page-title {
        font-weight: bold;
        font-size: 20px;
    }
}
</style>
